package com.unhz.taigu.service.impl;


import com.unhz.generator.dao.SysRolePermissionMapper;
import com.unhz.generator.dao.TryOrderMapper;

import com.unhz.generator.enums.EnumTryOrder;
import com.unhz.generator.pojo.*;
import com.unhz.generator.utils.EmptyUtil;
import com.unhz.generator.utils.IsNumeric;
import com.unhz.generator.utils.Page;

import com.unhz.generator.vo.AddTryOrderFindVo;
import com.unhz.generator.vo.TryOrderVo;
import com.unhz.generator.vo.UserVo;
import com.unhz.taigu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;

/**
 * @Author: 魏运奇
 * @Description:
 * @Date: Created in 下午 5:45 2018/1/31 0031
 * @Modified By: V1.0.0
 */
@Service
public class TryOrderServiceImpl implements TryOrderService{
    static final int PAGENUM = 1;


    @Autowired
    private TryOrderMapper tryOrderMapper;
    @Autowired
    private TryOrderInfoService tryOrderInfoService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private ReceivingInfoService receivingInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public Page<TryOrder> selectTryOrderList(String pageNo, Integer pageSize, String keywords,Integer adminId,Integer roleId) {
        int pageNum = PAGENUM;
        boolean numok = IsNumeric.isNumeric(pageNo);
        if(numok){
            if(Integer.parseInt(pageNo)<=0){
                pageNo="1";
            }
            if(pageNo !=null && !"".equals(pageNo)){
                pageNum = Integer.parseInt((pageNo));
            }
        }
        //查询roleId中是否存在permissionId对应值的权限
        int count = sysRolePermissionMapper.selectPermissionIdByRoleIdOrder(roleId);
        //获取记录总条数
        int totalRecords = 0;
        if(1==count){
            totalRecords =tryOrderMapper.getTotalRecordsByKeywords(keywords);      //获取记录总条数
        }else{
            totalRecords = tryOrderMapper.getTotalRecordsByKeywordsByAdminId(adminId,keywords);
        }

        Page page = new Page(pageNum,totalRecords);
        page.setPageSize(pageSize);
        Map<String ,Object> map = new HashMap<String,Object>();
        map.put("startIndex",page.getStartIndex());
        map.put("pageSize",page.getPageSize());
        map.put("keywords",keywords);
        map.put("adminId",adminId);
        //获取总记录数
        List<TryOrderVo> records = new ArrayList<TryOrderVo>();
        if(1==count){
            records = tryOrderMapper.selectTryOrder(map);
        }else{
            records = tryOrderMapper.selectTryOrderByAdminId(map);
        }
          //获得每个试做订单的试做信息
          for(TryOrderVo tryOrderVo:records){
              List<TryOrderInfo> infoList=tryOrderInfoService.selectTryOrderInfoList(Integer.parseInt(tryOrderVo.getId()));
              tryOrderVo.setTryOrderInfoList(infoList);
          }
        page.setRecords(records);
        //设置访问路径(分页)
        String url = "/tryOrder/selectList?keywords=";

        //StringBuffer strUrl=new StringBuffer("/tryOrder/selectList?keywords=");
        if(!EmptyUtil.isEmpty(keywords)){
            url=url+keywords;
        }
        if(!EmptyUtil.isEmpty(roleId)){
            url=url+"&roleId="+roleId;
        }
        if(!EmptyUtil.isEmpty(adminId)){
            url=url+"&adminId="+adminId;
        }
        page.setUri(url);

        return page;
    }

    @Override
    public List<TryOrderVo> selectTryOrder(HashMap<String, Object> map) {
        return null;
    }


    @Override
    public void changsStatus(Long id, Integer status,Date finishTime) {

          tryOrderMapper.changsStatus(id,status,finishTime);
    }

    @Override
    public boolean deleteById(Long id) {
        return tryOrderMapper.deleteById(id);
    }

    /**
     *添加试做订单
     * @param tryOrderVo
     * @return
     */
    @Override
    public Integer insert(TryOrderVo tryOrderVo) {
        Integer number=Integer.parseInt(tryOrderVo.getNumber());
       TryOrder tryOrder=new TryOrder();
       TryOrderInfo tryOrderInfo=new TryOrderInfo();
        //得到订单对象
        Order order= orderService.selectOrderById(Integer.parseInt(tryOrderVo.getOrderId()));
        //把vo转为pojo
        Integer orderId = Integer.parseInt(tryOrderVo.getOrderId());
        tryOrder.setOrderId(orderId);
        tryOrder.setSampleId(order.getSampleId());
       tryOrder.setTryNo(order.getOrderNo()+"A");   //试做订单号
       tryOrder.setSizeType(order.getSizeType());
       tryOrder.setUserPhone(tryOrderVo.getUserPhone());
       tryOrder.setUserName(tryOrderVo.getUserName());
       tryOrder.setProvince(tryOrderVo.getProvince());
       tryOrder.setCity(tryOrderVo.getCity());
       tryOrder.setCounties(tryOrderVo.getCounties());
        tryOrder.setAddress(tryOrderVo.getAddress());
        tryOrder.setStatus(EnumTryOrder.APPLICATION.getIndex());  //(1 申请试做 2 试做中 3 试做完成）
/*        //查询最大的试做id
        TryOrder tryOrder1= tryOrderMapper.selectMaxId();
        Long value;
        if(!EmptyUtil.isEmpty(tryOrder1)){
             tryOrder1.getId();
        }*/
        tryOrderMapper.insertSelective(tryOrder);    //添加试做订单
        //根据订单id查询刚刚添加的试做信息
       // TryOrder tryOrder1=tryOrderMapper.selectByOrderId(orderId);
        Integer key = tryOrder.getId();
        System.out.print("添加的主键为："+key);

        //添加试做信息
        List<Contract> contracts=contractService.findContractsByOrderId(orderId.intValue());
        for(Contract contract:contracts){
            tryOrderInfo.setSize(contract.getSize());
            tryOrderInfo.setNumber(number);
            tryOrderInfo.setTryId(key);
            tryOrderInfoService.insert(tryOrderInfo);
        }

        return EnumTryOrder.APPLICATION.getIndex();
    }

    //添加试做订单前查询
    @Override
    public AddTryOrderFindVo  selectTryOrderAdd(Long orderId) {
        AddTryOrderFindVo addTryOrderFindVo= tryOrderMapper.selectTryOrderAdd(orderId);
        //进行两种情况判断  判断是否有收货地址

        ReceivingInfo receivingInfo=receivingInfoService.selectByUserId(Integer.parseInt(addTryOrderFindVo.getUserId()));

        if(!(EmptyUtil.isEmpty(receivingInfo))) {   //如果收货地址非空，有修改的情况下
            addTryOrderFindVo.setStorageProvince(receivingInfo.getProvince());
            addTryOrderFindVo.setStorageCity(receivingInfo.getCity());
            addTryOrderFindVo.setStorageCounties(receivingInfo.getCounties());
            addTryOrderFindVo.setStorageAddress(receivingInfo.getAddress());
            addTryOrderFindVo.setUserPhone(receivingInfo.getUserPhone());
            addTryOrderFindVo.setUserName(receivingInfo.getUserName());
        }else{    //如果收货地址为空，默认用户仓库地址
            UserVo user=userService.findUserById(Integer.parseInt(addTryOrderFindVo.getUserId()));
             addTryOrderFindVo.setStorageProvince(user.getStorageProvince());
        addTryOrderFindVo.setStorageCity(user.getStorageCity());
        addTryOrderFindVo.setStorageCounties(user.getStorageCounties());
        addTryOrderFindVo.setStorageAddress(user.getStorageAddress());
        addTryOrderFindVo.setUserPhone(user.getUserPhone());
        addTryOrderFindVo.setUserName(user.getUserName());

        }
        String size="";
        //添加试做信息
        List<Contract> contracts=contractService.findContractsByOrderId(orderId.intValue());
        StringBuffer stringBuffer=new StringBuffer();
        for(Contract contract:contracts){
            stringBuffer.append(contract.getSize()+",");
        }
        size=stringBuffer.toString().substring(0,stringBuffer.length()-1);
        addTryOrderFindVo.setSize(size);

        return addTryOrderFindVo;
    }

    //修改试做地址
    @Override
    public boolean updateAddress(AddTryOrderFindVo addTryOrderFindVo) {
      //查询收货信息最新的一条数据
        ReceivingInfo receivingInfo=receivingInfoService.findByUserId(Integer.parseInt(addTryOrderFindVo.getUserId()));
        int flag=0;
        if(!(EmptyUtil.isEmpty(addTryOrderFindVo))) {
            if (EmptyUtil.isEmpty(receivingInfo)) {   //如果为空则为首次修改收货地址，根据业务需求添加一条收货信息
                flag = resolveVo(receivingInfo, addTryOrderFindVo);
            } else {      //如果不为空，则不是第一次修改收货地址   则进行地址判断
                if (receivingInfo.getUserName().trim().equals(addTryOrderFindVo.getUserName().trim()) &&
                        receivingInfo.getUserPhone().trim().equals(addTryOrderFindVo.getUserPhone().trim()) &&
                        receivingInfo.getProvince().trim().equals(addTryOrderFindVo.getStorageProvince().trim()) &&
                        receivingInfo.getCity().trim().equals(addTryOrderFindVo.getStorageCity().trim()) &&
                        receivingInfo.getCounties().trim().equals(addTryOrderFindVo.getStorageCounties().trim()) &&
                        receivingInfo.getAddress().trim().equals(addTryOrderFindVo.getStorageAddress().trim())) {
                    flag=1;
                } else {
                    flag = resolveVo(receivingInfo, addTryOrderFindVo);
                }
            }
        }
          if(flag>0){
               return true;
          }
         return false;
    }

    @Override
    public int updateInfo(TryOrder tryOrder) {
        return tryOrderMapper.updateByPrimaryKeySelective(tryOrder);
    }

    @Override
    public TryOrder selectByOrderId(Integer orderId) {
        return tryOrderMapper.selectByOrderId(orderId);
    }

    @Override
    public int insertTryOrder(TryOrder tryOrder) {
        return tryOrderMapper.insertSelective(tryOrder);
    }

    @Override
    public TryOrder selectTryOrder(Long id) {
        return tryOrderMapper.selectByPrimaryKey(id);
    }

    //添加收货信息
      public  int resolveVo(ReceivingInfo receivingInfo,AddTryOrderFindVo addTryOrderFindVo){
               int flag=0;
            //解析vo
                 receivingInfo=new ReceivingInfo();
                 receivingInfo.setUserId(Integer.parseInt(addTryOrderFindVo.getUserId()));
                 receivingInfo.setUserName(addTryOrderFindVo.getUserName());
                 receivingInfo.setUserPhone(addTryOrderFindVo.getUserPhone());
                 receivingInfo.setProvince(addTryOrderFindVo.getStorageProvince());
                 receivingInfo.setCity(addTryOrderFindVo.getStorageCity());
                 receivingInfo.setCounties(addTryOrderFindVo.getStorageCounties());
                 receivingInfo.setAddress(addTryOrderFindVo.getStorageAddress());
                 flag=receivingInfoService.insertAddress(receivingInfo);
            return flag;
      }

}
